package com.aube.control.mediaproxy;

import java.util.HashMap;

/**
 * 端口管理器,每次新建NanoHTTPD代理的时候都从这里分配端口
 * Created by huyaonan on 16/8/17.
 */
public class PortManager {

    private static int port = 9000;

    private static HashMap<Integer, Integer> mPortInUse = new HashMap<>();

    public static int getPort() {
        if(mPortInUse == null)
            mPortInUse = new HashMap<>();
        while (mPortInUse.containsKey(port))
            port++;
        if(port >= 65535)
            return -1;
        mPortInUse.put(port, port);
        return port;
    }

    public static void onDestroy() {
        if(mPortInUse != null)
            mPortInUse.clear();
        port = 9000;
    }

    public static void releasePort(int port) {
        if(port < 9000)
            return;
        if(mPortInUse != null && mPortInUse.containsKey(port))
            mPortInUse.remove(port);
    }

}
